package de.dopichaj.labrador.search;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.apache.commons.lang.Validate;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.xml.resolver.tools.CatalogResolver;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

import de.dopichaj.labrador.index.lucene.LuceneFileSystemIndex;
import de.dopichaj.labrador.search.hit.Hit;
import de.dopichaj.labrador.search.hit.RemoteHit;
import de.dopichaj.labrador.search.merge.pattern.InertiaPattern;
import de.dopichaj.labrador.search.merge.pattern.InlinePattern;
import de.dopichaj.labrador.search.merge.pattern.PatternMerge;
import de.dopichaj.labrador.search.merge.pattern.TitlePattern;
import de.dopichaj.labrador.search.prune.ContextPruner;
import de.dopichaj.labrador.search.prune.FuzzyLengthBasedPruner;
import de.dopichaj.labrador.search.prune.MultiPruner;
import de.dopichaj.labrador.search.prune.ResultTreePruner;
import de.dopichaj.labrador.util.AbortingExceptionHandler;


public final class RemoteSearcherImpl extends UnicastRemoteObject
    implements RemoteSearcher {

    private static final long serialVersionUID = 1L;
    private static final Logger log = Logger.getLogger(RemoteSearcherImpl.class);

    private final transient XMLSearcher searcher;
    private final transient Transformer transformer;
    private final transient XPath xPath = XPathFactory.newInstance().newXPath();
    
    private RemoteSearcherImpl(XMLSearcher searcher) throws RemoteException,
        TransformerConfigurationException,
        TransformerFactoryConfigurationError {
        super();
        
        this.searcher = searcher;
        this.transformer = TransformerFactory.newInstance().newTransformer();
    }

    public RemoteHit[] search(String nexi, int n)
        throws SearchException, QueryParseException {

        Validate.notNull(nexi);
        Validate.isTrue(n >= 1);
        
        log.info("Searching for " + nexi);
        
        List<Hit> hits = searcher.search(nexi);
        log.info("Got " + hits.size() + " hits");
        Iterator<Hit> it = hits.iterator();
        RemoteHit[] result = new RemoteHit[Math.min(n, hits.size())];
        for (int i = 0; i < n && it.hasNext(); i++) {
            Hit hit = it.next();

            result[i] = new RemoteHit(hit, getFragment(hit.getFile(), hit.getXPath()));
        }
        return result;
    }

    public String getFragment(File file, String xPathExpression) {
        
        Validate.notNull(file);
        Validate.notNull(xPathExpression);
        
        try {
            DocumentBuilder builder =
                DocumentBuilderFactory.newInstance().newDocumentBuilder();
            builder.setEntityResolver(new CatalogResolver());
            
            Document doc = builder.parse(file);
            
            Node fragment = (Node)xPath.evaluate(xPathExpression, doc,
                XPathConstants.NODE);
            StringWriter result = new StringWriter();
            transformer.transform(
                new DOMSource(fragment), new StreamResult(result));
            return result.toString();
        } catch (DOMException e) {
            log.error("Error getting fragment from " + file, e);
        } catch (ParserConfigurationException e) {
            log.error("Error getting fragment from " + file, e);
        } catch (SAXException e) {
            log.error("Error getting fragment from " + file, e);
        } catch (IOException e) {
            log.error("Error getting fragment from " + file, e);
        } catch (TransformerException e) {
            log.error("Error getting fragment from " + file, e);
        } catch (XPathExpressionException e) {
            log.error("Error getting fragment from " + file, e);
        }
        return "[could not get fragment]";
    }
    
    public static void main(String[] args) throws Exception {

        Thread.setDefaultUncaughtExceptionHandler(new AbortingExceptionHandler());

        File propertiesFile = new File(args[0]);
        InputStream propertiesStream = new FileInputStream(propertiesFile);
        Properties properties = new Properties();
        properties.load(propertiesStream);

        File indexDirectory =
            new File(properties.getProperty("de.dopichaj.labrador.index", "de.dopichaj.labrador.index"));
        int port;
        if (properties.getProperty("port") != null) {
            port = Integer.parseInt(properties.getProperty("port"));
        } else {
            port = DEFAULT_PORT;
        }
        
        ResultTreePruner pruner = new MultiPruner(
            new ContextPruner(new PatternMerge(
            new TitlePattern(), new InlinePattern(), new InertiaPattern())),
            new FuzzyLengthBasedPruner());
        XMLSearcher searcher = new XMLSearcher(
            new LuceneFileSystemIndex(indexDirectory).getNEXISearcher(), pruner);
        RemoteSearcher server = new RemoteSearcherImpl(searcher);

        Registry registry = LocateRegistry.createRegistry(port);
        registry.rebind(DEFAULT_NAME, server);
        System.err.println("Server up and running. Enter 'quit' to quit.");

        BufferedReader reader =
            new BufferedReader(new InputStreamReader(System.in));
        String line;
        while ((line = reader.readLine()) != null) {
            final String[] tokens = line.split("\\s+");
            final String command = tokens[0];
            if (command.equals("quit")) {
                break;
            } else if (command.equals("debug")) {
                for (int i = 1; i < tokens.length; i++) {
                    final String classString = tokens[i];
                    final Logger logger = Logger.getLogger(classString);
                    logger.setLevel(Level.DEBUG);
                }
            } else {
                System.err.println("Unknown command: " + command);
            }
        }
        System.err.println("Exiting ...");
        registry.unbind(DEFAULT_NAME);
        UnicastRemoteObject.unexportObject(registry, true);
        UnicastRemoteObject.unexportObject(server, true);
    }
}
/*
Copyright (c) 2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/